from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
from django.core.paginator import Paginator


def tab():
    cates = models.Shang.objects.extra(select={'newpath': 'concat(paths,id)'}).order_by('newpath')
    for i in cates:
        num = i.paths.count(',') - 1
        i.newname = num * '|----'
    return cates


def tianjia(request):
    if request.method == 'GET':
        # 将所有的类型返回
        cates = tab()

        return render(request, 'myadmin/wupin/tianjia.html', {'cates': cates})
    elif request.method == 'POST':
        # 接受pid 通过pid来判断是不是顶级分类
        pid = request.POST.get('pid')
        name = request.POST.get('name')
        print(pid)
        print(name)
        if pid == '0':
            cate = models.Shang()
            cate.name = name
            cate.upid = int(pid)
            cate.paths = '0,'
            cate.save()
        else:
            # 根据pid找父级 paths
            pobj = models.Shang.objects.get(id=pid)
            c = models.Shang()
            c.name = name
            c.upid = pobj.id
            c.paths = pobj.paths + pid + ','
            c.save()

        # 接受数据添加数据
        cates = tab()
        return render(request,'myadmin/wupin/fenlei.html', {'cates': cates})


def fenlei(request):
    # 查询所有的分类
    # cates = models.Cates.objects.all()
    # select *,concat(paths,id) as newpath  from myadmin_cates order by newpath;
    # 模型提供 extra
    # cates = models.Cates.objects.extra(select = {'newpath':'concat(paths,id)'}).order_by('newpath')

    # for i in cates:
    #     num = i.paths.count(',')-1
    #     i.newname=num*'|----'
    cates = tab()

    return render(request, 'myadmin/wupin/fenlei.html', {'cates': cates})


def delcate(request):
    # 接受id
    pid = int(request.GET.get('pid'))
    # 判断有没有子分类
    cnum = models.Shang.objects.filter(upid=pid).count()
    if cnum:
        return JsonResponse({'msg': 0})
    else:
        c = models.Shang.objects.get(id=pid)
        c.delete()
        return JsonResponse({'msg': 1})


# 修改
def editcate(request):
    # 接受id和name
    cid = int(request.GET.get('id'))
    cname = request.GET.get('name')
    try:
        cate = models.Shang.objects.get(id=cid)
        cate.name = cname
        cate.save()
        return JsonResponse({'msg': 1})
    except:
        return JsonResponse({'msg': 0})